import CommonHelper from '../utils/common.helper'
import { PlatformBaseManager } from './platform-base'

export default class AlibabaManager extends PlatformBaseManager {
  init() {
    this.getProductInfo()
      .then((productInfo) => {
        CommonHelper.log('product detected', productInfo)

        let button = jQuery(
          '<button class="btn btn-primary">下载图片展示页</button>'
        )
        button.prependTo(document.body)
        button.on('click', () => {
          this.saveProductInfo(productInfo)
          //downloadFile(renderProductContent(productInfo), productInfo.title + '.html')
        })
      })
      .catch((err) => {})
  }
  getProductInfo(): Promise<ProductInfo> {
    let videoList = $<HTMLVideoElement>('video.lib-video')
      .map((_, video) => {
        return {
          src: video.src,
          poster: video.poster,
          duration: video.duration,
        }
      })
      .get()

    let tierList = $('.obj-sku')
      .map((_, item) => {
        return {
          title: $(item).find('.obj-title').text(),
          options: $(item)
            .find('.image')
            .map((_, item) => {
              let title = $(item).attr('title') || ''
              let imgUrl = $(item).data().imgs.original
              let suffix = imgUrl.split('.').pop()
              return {
                title: title,
                imgUrl: imgUrl,
                fileName: title + '.' + suffix,
              }
            })
            .get(),
        }
      })
      .get()

    let imgList = $('.tab-trigger[data-imgs]')
      .map((index, item) => ({
        imgUrl: $(item).data().imgs.original,
        title: 'main_' + index,
        fileName: 'main_' + index + '.jpg',
      }))
      .get()
      .filter((img) => {
        return !tierList.some((tier) => {
          return tier.options.some((option) => option.imgUrl === img.imgUrl)
        })
      })

    let result: ProductInfo = {
      title: 'ali_' + $('#mod-detail-title > h1').text(),
      href: location.href,
      videoList: videoList,
      imgList,
      tierList,
    }
    return Promise.resolve(result)
  }
}
